package com.sig.signomadeConnected;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sig.sigandroid.R;
import com.sig.webservice.ParseAllName;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class ConnectedActivity extends Activity {
	/**
	 * the widgets
	 */
	private AutoCompleteTextView textView;
	private AutoCompleteTextView textView2;
	private AutoCompleteTextView textView3;
	
	/**
	 * the begin point and destination point
	 */
	private String position;
	private String destination;
	
	/**
	 * Path to server and file
	 */
	private static String stringUrl="http://192.168.43.197:8080/sig.provider.service/provider/todo";
	public static final String PATH_FILE_XML = "/data/map.xml";

	/**
	 * TAG
	 */
	private final String TAG = "TAG";

	/**
	 * Default value for AutocompletTextView
	 */

	private static String[] name={"Where?"};
	
	
	/**
	 * Url to the server
	 */
	private static final String[] URL = new String[] {
			"http://192.168.43.197:8080/sig.provider.service/provider/hello",
			"http://192.168.43.197:8080/sig.provider.service/provider/todo" };


	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_connected);
		new DownloadWebpageTask().execute(stringUrl);
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, URL);
		textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
		textView2 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
		textView3 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView3);
		textView3.setAdapter(adapter2);
		textView.setOnFocusChangeListener(new MyFocusListener());

	}

	public void onmap(View v) {
		Intent intent = new Intent(this, WebActivity.class);
		startActivity(intent);
	}

	public void askServer(View v) {
		stringUrl = textView3.getText().toString();
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		doTaskConnection(networkInfo);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, name);
		textView.setAdapter(adapter);
		textView2.setAdapter(adapter);
	}

	public void ongo(View v) {
		Log.d(TAG, "connect to the server " + textView3.getText().toString());
		
	}

	public void clean(View v) {
		textView.setText("");
	}

	@SuppressLint("ShowToast")
	public void doTaskConnection(NetworkInfo networkInfo) {
		if (networkInfo != null && networkInfo.isConnected()) {
			new DownloadWebpageTask().execute(stringUrl);
			Toast.makeText(this, "Connecting to server...",
					Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, "No connection", Toast.LENGTH_LONG).show();
		}
	}


	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.connected, menu);
		return true;
	}

	private String downloadUrl(String myurl) throws IOException {
		InputStream is = null;
		// Only display the first 500 characters of the retrieved
		// web page content.
		int len = 500;

		try {
			URL url = new URL(myurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			int response = conn.getResponseCode();
			Log.d("TAG", "The response is: " + response);
			is = conn.getInputStream();

			// Convert the InputStream into a string
			String contentAsString = readIt(is, len);
			return contentAsString;

			// Makes sure that the InputStream is closed after the app is
			// finished using it.
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	public String readIt(InputStream stream, int len) throws IOException,
			UnsupportedEncodingException {
		return getStringFromInputStream(stream);
	}

	private static String getStringFromInputStream(InputStream is) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return sb.toString();
	}

	private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {

			// get here the data from BDD
			try {
				return downloadUrl(urls[0]);
			} catch (IOException e) {
				Log.d("TAG", "Unable to retrieve web page. URL may be invalid.");
				return null;
			}
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(String result) {
			// ParseJson p = new ParseJson(result);
			StringBuffer buff = new StringBuffer();
			buff.append(result);

			File file = writeFileToInternalStorage(result);
			ParseAllName parse = new ParseAllName();
			parse.load(file, parse);
			name = parse.getStructure().getName()
					.toArray(new String[parse.getStructure().getName().size()]);
			
			
			Log.d("STRUCTURE", "" + parse.getStructure().getName().size());
			Log.d("RESULT", "" + result);
		}
	}

	public class MyFocusListener implements OnFocusChangeListener {

		public void onFocusChange(View v, boolean hasFocus) {
			switch (v.getId()) {
			case R.id.textView1:
				if (hasFocus) {
					textView.setText("");
				}
				break;

			}

		}

	}

	private File writeFileToInternalStorage(String result) {
		BufferedWriter writer = null;
		File file = null;
		try {
			File cacheDir = getCacheDir();
			file = new File(cacheDir, "map.xml");
			FileWriter fileWriter = new FileWriter(file);
			writer = new BufferedWriter(fileWriter);
			writer.write(result);
			Log.d("WRITE TO", "internal storage" + file.getAbsolutePath()
					+ " the is created at" + file.getName());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return file;
	}

}
